import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/account/models/user_response.dart';
import 'package:edu/pages/common/empty_content_widget.dart';
import 'package:edu/pages/profile/location_setting/location_setting_page_logic.dart';
import 'package:edu/utils/app_router.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

class LocationSettingPage extends StatefulWidget {
  const LocationSettingPage({super.key});

  @override
  State<LocationSettingPage> createState() => _LocationSettingPageState();
}

class _LocationSettingPageState extends State<LocationSettingPage> {
  @override
  void initState() {
    super.initState();

    context.read<LocationSettingPageLogic>().init();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<LocationSettingPageLogic>(
      builder: (context, logic, child) {
        return Scaffold(
          appBar: _buildAppBar(context, logic),
          body: _buildMainBody(context, logic),
        );
      },
    );
  }

  // 通过 logic 对象获取数据和处理事件，同时遵循了主题样式的一致性
  AppBar _buildAppBar(BuildContext context, LocationSettingPageLogic logic) {
    final fontSize =
        (Theme.of(context).appBarTheme.titleTextStyle?.fontSize ?? 20) - 2;
    final title = logic.title ?? AppStrings.selectRegion;
    return AppBar(
      title: Text(title),
      actions: [
        TextButton(
          onPressed: logic.selectedCode != null ? _okAction : null,
          child: Text(AppStrings.ok, style: TextStyle(fontSize: fontSize)),
        ),
      ],
    );
  }

  //据不同的数据状态（加载中、错误、空数据、有数据）
  //展示对应的界面，同时处理了可能的空指针问题（使用??运算符）
  Widget _buildMainBody(BuildContext context, LocationSettingPageLogic logic) {
    final regions = logic.regions;
    if (regions?.isEmpty ?? true) {
      return EmptyContentWidget(
        isLoading: logic.isLoading,
        isError: logic.isError,
        reloadAction: logic.loadRegions,
      );
    } else {
      return _buildRegionList(context, logic);
    }
  }

  // 构建地区列表
  Widget _buildRegionList(
    BuildContext context,
    LocationSettingPageLogic logic,
  ) {
    final regions = logic.regions;
    final Color dividerColor;
    // 获取主题色
    if (Theme.of(context).brightness == Brightness.light) {
      dividerColor = Colors.grey[200]!;
    } else {
      dividerColor = Colors.grey[800]!;
    }

    // 构建列表
    return ListView.separated(
      // 分割线
      separatorBuilder: (context, index) => Padding(
        padding: const EdgeInsets.only(left: 15, right: 20),
        child: Divider(height: 0.25, color: dividerColor),
      ),
      itemCount: regions!.length,
      // 通过条件判断动态展示不同状态的列表项，实现了选择状态显示、
      // 权限控制（通过等级判断）和交互响应功能
      itemBuilder: (context, index) {
        final region = regions[index];
        return ListTile(
          // 标题
          title: Text(region.name),
          // 描述
          trailing: logic.selectedCode == region.code
              ? Icon(Icons.check, color: Theme.of(context).colorScheme.primary)
              : logic.level < 5 && region.category != 10000
              ? Icon(Icons.arrow_forward_ios, color: dividerColor, size: 15)
              : null,
          onTap: () {
            _regionRowTapped(region, logic);
          },
        );
      },
    );
  }

  // 处理地区行点击事件,当点击某个地区且满足条件时，会进入该地区的下一级地区列表页面
  void _regionRowTapped(ChinaRegion region, LocationSettingPageLogic logic) {
    logic.selectRegion(region);
    if (logic.level < 5 && region.category != 10000) {
      context.pushNamed(
        AppRouter.kLocationSetting,
        queryParameters: {
          'code': region.code,
          'level': '${logic.level + 1}',
          'title': region.name,
        },
      );
    }
  }

  // 处理确定按钮点击事件
  void _okAction() {
    final logic = context.read<LocationSettingPageLogic>();
    logic.updateRegion().then((value) {
      if (value && mounted) {
        Navigator.of(context).popUntil((route) {
          // 点击确认按钮后，更新地区设置，成功后返回到账户设置页面
          return route.settings.name == AppRouter.kAccountProfileSetting;
        });
      }
    });
  }
}
